package com.smit.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.Charset;

import android.content.Context;

/**
 * File工具类
 */
public final class FileUtil {
    private static final String TAG = "FileUtil";

    private FileUtil() { }
    /**
     * 写入object对象到文件
     * @param context Android application context
     * @param fileName 文件名（默认写入 files 下）
     * @param obj object对象
     * @throws Exception 文件读写异常
     */
    public static void writeObject(Context context, String fileName, Object obj) throws Exception {
        if (obj == null) {
            return;
        }
        String path = context.getFilesDir() + "/";
        File dir = new File(path);
        dir.mkdirs();

        File f = new File(dir, fileName);

        if (f.exists()) {
            f.delete();
        }
        FileOutputStream os = new FileOutputStream(f);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(os);
        objectOutputStream.writeObject(obj);
        objectOutputStream.flush();
        objectOutputStream.close();
        os.close();
    }

    /**
     * 从文件读取object对象
     * @param context Android application context
     * @param fileName 文件名（默认路径是 包名/files/）
     * @return Object对象
     * @throws Exception 文件读写异常
     */
    public static Object readObject(Context context, String fileName) throws Exception {
        String path = context.getFilesDir() + "/";
        File dir = new File(path);
        //dir.mkdirs();
        File file = new File(dir, fileName);
        InputStream is = new FileInputStream(file);

        ObjectInputStream objectInputStream = new ObjectInputStream(is);

        Object object = objectInputStream.readObject();

        objectInputStream.close();

        return object;

    }

    /**
     * 从文件读取object对象
     * @param filePath 文件全路径
     * @return Object对象
     * @throws Exception 文件读写异常
     */
    public static Object readObject2(String filePath) throws Exception {
        File file = new File(filePath);
        InputStream is = new FileInputStream(file);

        ObjectInputStream objectInputStream = new ObjectInputStream(is);

        Object o = objectInputStream.readObject();

        objectInputStream.close();

        return o;

    }

    /**
     * 写入string到文件
     * @param context Android application context
     * @param fileName 文件名（默认路径是 包名/files/）
     * @param dataStr string数据
     * @throws Exception 文件读写异常
     */
    public static void writeString(Context context, String fileName, String dataStr) throws Exception {
        String path = context.getFilesDir() + "/";
        File dir = new File(path);
        dir.mkdirs();
        File file = new File(dir, fileName);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out = new FileOutputStream(file);
        out.write(dataStr.getBytes(Charset.defaultCharset()));
        out.flush();
        out.close();
    }

    /**
     * 写入string到文件
     * @param context Android application context
     * @param filePath 文件全路径
     * @param dataStr string数据
     * @throws Exception 文件读写异常
     */
    public static void writeString2(Context context, String filePath, String dataStr) throws Exception {
        String path = context.getFilesDir() + "/";
        File dir = new File(path);
        dir.mkdirs();
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out = new FileOutputStream(file);
        out.write(dataStr.getBytes(Charset.defaultCharset()));
        out.flush();
        out.close();
    }

    /**
     * 将asset中数据拷贝到本地文件
     * @param context Android application context
     * @param assetsFilePath assets中文件全路径
     * @param localCopyPath 本来文件全路径
     * @return true成功，false失败
     * @throws IOException 文件读写异常
     */
    public static boolean copyAssetsFile2Local(Context context, String assetsFilePath, String localCopyPath)
            throws IOException {
        LogUtil.debug(TAG, "copyAssetsFile2Local start ");
        LogUtil.debug(TAG, "copyAssetsFile2Local assetsFilePath=" + assetsFilePath);
        InputStream assetsStream = null;
        FileOutputStream fos = null;
        //        if (isFileInAssets(context, assetsFilePath) == false)
        //        {
        //            LogUtil.Logd(TAG, "isFileInAssets return false !");
        //            return false;
        //        }
        assetsStream = context.getAssets().open(assetsFilePath);
        fos = new FileOutputStream(localCopyPath);
        LogUtil.debug(TAG,
                "copyAssetsFile2Local assetsFilePath=" + assetsFilePath + " and size  " + assetsStream.available());
        byte[] buffer = new byte[1024];
        while (true) {
            int len = assetsStream.read(buffer);
            if (len == -1) {
                break;
            }
            fos.write(buffer, 0, len);
        }
        assetsStream.close();
        fos.flush();
        fos.close();
        return true;
    }

    /**
     * 判断文件是否在assets中
     * @param context Android application context
     * @param assetsFilePath 文件全路径
     * @return true存在，false不存在
     * @throws IOException 文件读写异常
     */
    public static boolean isFileInAssets(Context context, String assetsFilePath) throws IOException {
        LogUtil.debug(TAG, "isFileInAssets start ");
        String[] fileNames = null;
        fileNames = context.getResources().getAssets().list(assetsFilePath);
        if (fileNames == null) {
            LogUtil.error(TAG, "isFileInAssets fileNames is null");
            return false;
        }
        for (int i = 0; i < fileNames.length; i++) {
            LogUtil.debug(TAG, "isFileInAssets fileName=" + fileNames[i].trim());
            String name = fileNames[i].trim();
            String fileName = assetsFilePath.trim();
            if (name.equals(fileName)) {
                LogUtil.trace(TAG, "isFileInAssets has found assetsFilePath" + assetsFilePath);
                return true;
            }
        }
        return false;
    }
}
